package com.programmercarl.array;

import java.util.Arrays;

/**
 * https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/
 *
 * @author yulongtian
 * @create 2024-12-10 10:33
 */
public class Test03 {
    public static void main(String[] args) {
//        int[] nums = {5, 7, 7, 8, 8, 10};
        int[] nums = {1};
        System.out.println(Arrays.toString(searchRange(nums, 0)));
    }

    public static int[] searchRange(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return new int[]{-1, -1};
        }
//        if (nums.length == 1) {
//            if (target == nums[0]) {
//                return new int[]{0, 0};
//            } else {
//                return new int[]{-1, -1};
//            }
//        }
        int[] result = new int[2];
        result[0] = searchRange2(nums, target, true);
        result[1] = searchRange2(nums, target, false);

        return result;
    }

    public static int searchRange2(int[] nums, int target, boolean is_left) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                if (is_left) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            }
        }
        if (is_left) {
            return left < nums.length && nums[left] == target ? left : -1;
        } else {
            return right >= 0 && nums[right] == target ? right : -1;
        }
    }

}
